<template>
    <div>
        <Row class="topBar">
            <Col span="4" style="padding-left:10px;font-weight:700;color:#5b5b5b;">员工管理</Col>
            <Col span="2" offset="18">
                <Button class="btn-in-top-large" style="margin-right:0px" @click="addPeople()" type="primary" v-if="canAddStaff">添加员工</Button>
                <Button class="btn-in-top-large" style="margin-right:100px" @click="exportPeopleDetai" type="primary">导出员工明细</Button>
            </Col>
        </Row>
        <Row class="range">
            <Col span="24">
            <Row type="flex" justify="space-between" align="middle" :gutter="16">

                <Col span="7">
                    <Select v-model="branch" placeholder="门店" clearable @on-change="search(1)">
                        <Option v-for="item in branches" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </Col>

                <Col span="7">
                    <Select v-model="role" placeholder="角色" clearable @on-change="search(1)">
                        <Option v-for="item in roles" v-if="item.id!=100" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </Col>

                <Col span="10">
                    <Input v-model.trim="keyword" icon="ios-search-strong" @on-enter="search" @on-click="search" placeholder="关键字：员工姓名/手机号"></Input>
                </Col>
            </Row>
            </Col>
        </Row>
        <Table :loading="loading" class="no-btn-border" border ref="selection" :columns="columns4" :data="data1"></Table>
        <!-- <Button @click="handleSelectAll(true)">全选</Button>
        <Button @click="handleSelectAll(false)">取消全选</Button> -->

        <Page :current.sync="offset" @on-change="pageChange" :total="total" :page-size="limit" show-elevator show-total style="text-align:center"></Page>
        <peopleModal
        :modal="flag"
        @update=handleModal
        :userInfoReadonly="userInfoReadonly"
        :roles="roles"
        :roleId="roleId"
        @updateList="updateList"></peopleModal>
    </div>
</template>

<script>
import pickBy from 'lodash/pickBy'
import { date } from '@/filters'
import { mapGetters } from 'vuex'
import peopleModal from './peopleModal.vue'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
import util from '@/libs/util'

export default {
  data () {
    return {
      hasFaceAccessPms: false,
      loading: false,
      branches: [],
      branch: '',
      roles: [],
      limit: 20,
      total: 0,
      offset: 1,
      flag: false,
      roleId: '',
      keyword: '',
      role: '',
      userInfoReadonly: false,
      columns4: [
        // {
        //     type: 'selection',
        //     width: 60,
        //     align: 'center'
        // },
        {
          title: '姓名',
          key: 'name',
          align: 'center'
        },
        {
          title: '手机号码',
          key: 'telephone',
          align: 'center'
        },
        {
          title: '所属门店',
          key: 'shop',
          align: 'center',
          render: (h, params) => {
            if (params.row.branches.length === 0) {
              return h('p', '总部')
            } else {
              let res = ''
              params.row.branches.forEach((item, index) => {
                if (index === 0) {
                  res = res + item.name
                } else {
                  res = res + '、' + item.name
                }
              })
              return h('p', res)
            }
          }
        },
        {
          title: '角色',
          key: 'role',
          align: 'center',
          render: (h, params) => {
            return h('p', params.row.role.name)
          }
        },
        {
          title: '创建时间',
          key: 'role',
          align: 'center',
          render: (h, params) => {
            return h('span', date(params.row.role.created_at))
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 260,
          align: 'center',
          render: (h, params) => {
            const base = {
              props: {
                type: 'ghost',
                size: 'small'
              },
              style: {
                marginRight: '5px'
              }
            }
            return (
              <div>
                <i-button
                  {...base}
                  onClick={() => this.editPeople(params, true)}>
                                    查看
                </i-button>
                {
                  this.canEditStaff &&
                                    <i-button
                                      {...base}
                                      onClick={() => this.editPeople(params)}>
                                        编辑
                                    </i-button>
                }
                {
                  this.canDeleteStaff &&
                                    <i-button
                                      {...base}
                                      type='error'
                                      onClick={() => this.getHomesBeforeDelete(params)}>
                                        删除
                                    </i-button>
                }
                {
                  this.hasFaceAccessPermission &&
                                    <i-button
                                      {...base}
                                      type='error'
                                      onClick={() => this.accessControl(params.row)}>
                                        门禁授权
                                    </i-button>
                }
              </div>
            )
          }
        }
      ],
      data1: []
    }
  },

  computed: {
    ...mapGetters(['userCurrentPermissions', 'hasFaceAccessPermission']),
    canAddStaff () {
      if (!this.userCurrentPermissions) return false
      return this.userCurrentPermissions.some(p => (p.resource === 'user' && p.action === 'create'))
    },
    canEditStaff () {
      if (!this.userCurrentPermissions) return false
      return this.userCurrentPermissions.some(p => (p.resource === 'user' && p.action === 'update'))
    },
    canDeleteStaff () {
      if (!this.userCurrentPermissions) return false
      return this.userCurrentPermissions.some(p => (p.resource === 'user' && p.action === 'destroy'))
    }
  },

  methods: {
    // 搜索
    search (page) {
      if (page === 1) {
        this.offset = 1
      }
      this.getUsers()
    },

    initTab (arr) {
      if (this.$route.params.staffId) {
        const staffId = this.$route.params.staffId
        const staff = arr.find(item => item.id === staffId)
        this.$store.dispatch('addStaffTab', staff).then(() => {
          this.$router.push(`/staff/${staff.id}`)
        })
      }
    },

    // 分页
    pageChange (val) {
      this.offset = val
      this.getUsers()
    },

    handleSelectAll (status) {
      this.$refs.selection.selectAll(status)
    },

    // 获取门店
    getBrances () {
      dataCenter.getStores(this, (res, err) => {
        if (err || !res) {
          return
        }
        this.branches = res
      })
    },

    // 门禁授权打开新的页面
    accessControl (staff) {
      this.$store.dispatch('addStaffTab', staff).then(() => {
        this.$router.push(`/staff/${staff.id}`)
      })
    },

    // 获取角色
    getRoles () {
      http.request(this, api.role_list, null, { list_type: 'all' }, (res, err) => {
        if (err || !res) {
          return
        }
        this.roles = res.rows.sort((a, b) => {
          return a.id - b.id
        })
      })
    },

    // 添加用户
    addPeople () {
      this.userInfoReadonly = false
      this.flag = true
      this.roleId = ''
    },

    // 导出员工明细
    exportPeopleDetai () {
      const query = { download: true, ...this.getQuery() }
      http.exportTable(this, api.export_users_detai, null, query)
    },
    getQuery (hasPage) {
      const { offset, limit, branch: branch_id, role: role_id, keyword } = this
      const query = pickBy({ branch_id, role_id, keyword }, val => !!val)
      if (branch_id === 0) query.branch_id = 0
      if (hasPage) {
        query.list_type = 'page'
        query.limit = limit
        query.offset = (offset - 1) * limit
      }
      return query
    },
    // 获取全部用户
    getUsers () {
      this.loading = true
      const query = this.getQuery(true)
      http.request(this, api.user_list, null, query, (res, err) => {
        this.loading = false
        if (err || !res) {
          return
        }
        let clientCounts = 0
        this.data1 = res.rows.filter(item => {
          if (item.role_id === 100) {
            clientCounts += 1
          }
          return item.role_id !== 100
        })

        this.initTab(this.data1)
        this.total = res.count - clientCounts
      })
    },

    getHomesBeforeDelete (params) {
      const roleId = params.row.role_id
      if (roleId === 104) {
        this.$Modal.confirm({
          title: '删除管家',
          content: `确定要删除 <strong>${util.escapeHtml(params.row.role && params.row.role.name)} ${
            util.escapeHtml(params.row.name)
          }</strong> 吗?<br>管家删除后，将从原管理房源的管理者同步删除，请确认。`,
          okText: '删除',
          onOk: () => {
            this.delPeople(params)
          }
        })
      } else {
        this.$Modal.confirm({
          title: '删除用户',
          content: `确定要删除 <strong>${util.escapeHtml(params.row.role && params.row.role.name)} ${
            util.escapeHtml(params.row.name)
          }</strong> 吗?<br>删除后员工账号与公司绑定关系同步解除。<br>删除员工，不会同步删除员工的门禁授权，安全起见，<br>请在授权列表里面手动取消员工的授权。`,
          okText: '删除',
          onOk: () => {
            this.delPeople(params)
          }
        })
      }
    },

    // 删除用户
    delPeople (params) {
      let id = params.row.id
      http.request(this, api.user_del, [id], null, (res, err) => {
        if (err || !res) {
          return
        }
        this.$Message.success('删除成功')
        this.updateList()
      })
    },

    // 编辑用户
    editPeople (params, userInfoReadonly) {
      this.userInfoReadonly = userInfoReadonly
      this.flag = true
      this.roleId = params.row
    },

    // 更新列表
    updateList () {
      this.getUsers()
    },
    handleModal (val) {
      this.flag = val
    }
  },

  mounted () {
    if (this.$route.query.select) {
      this.branch = +this.$route.query.select
    }
    this.getUsers()
    this.getBrances()
    this.getRoles()

    // const hasFaceAccessPms = this.$store.state.user.hasFaceAccessPermission;
    // if (hasFaceAccessPms) {
    //     this.hasFaceAccessPms = true;
    // }
  },

  components: {
    peopleModal
  }
}
</script>

<style lang="less" scoped>
.topBar {
    color: #1c2438;
    font-size: 18px;
    line-height: 50px;
    width: 100%;
    height: 50px;
    background: #efeff1;
    border-left: 5px solid #05bac5;
    margin-bottom: 20px;
}
.range {
    margin-bottom: 20px;
}
</style>
